package com.controller;

import com.service.iml.UserService;
import com.utils.JwtTokenUtil;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import java.io.BufferedOutputStream;
import java.io.IOException;
import java.net.URLEncoder;

@RestController
@RequestMapping("/download")
public class DownloadController {

    @Resource
    private UserService userService;
    @Resource
    private JwtTokenUtil jwtTokenUtil;

    @GetMapping("/user/avatar")
    @ResponseBody
    public void downloadUserAvatar(HttpServletRequest request, HttpServletResponse response) throws IOException {
        String openid = jwtTokenUtil.getIdFromToken(request);
        byte[] avatar = userService.getUser(openid).getAvatar();
        if (avatar == null) {
            response.sendError(404, "头像不存在");
        } else {
            response.addHeader("Content-Disposition", "attachment; filename=" + URLEncoder.encode("头像.png", "UTF-8"));
            response.setContentType("image/png"); //必须设置内容类型
            BufferedOutputStream bos = new BufferedOutputStream(response.getOutputStream(), 8192 << 1);
            bos.write(avatar); //这里为 null 时报异常
            bos.flush();
            bos.close();
        }
    }

}
